<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/28 14:15
 * Remark:
 */

namespace App\Service\Login;

use App\Consts\RedisConsts\RedisConsts;
use App\Func\EncryptionFunc;
use App\Models\Auth\AuthStaffModel;
use App\Models\Staff\StaffDepartmentModel;
use App\Tools\Token\LoginToken;
use Illuminate\Support\Facades\Redis;

class LoginService
{
    private StaffDepartmentModel $_staffDepartmentModel;
    private AuthStaffModel $_staffAuthModel;

    public function __construct()
    {
        $this->_staffAuthModel = new AuthStaffModel();
        $this->_staffDepartmentModel = new StaffDepartmentModel();
    }

    /**
     * @param $staffId
     */
    public function getStaffDepartments($staffId){
        return $this->_staffDepartmentModel->getStaffDepartments($staffId);
    }


    public function loginDepartment($staffInfo): array
    {
        $staffId = $staffInfo['staff_id'];
        $companyId = $staffInfo['company_id'];
        // 处理数据给每个数据设置Token
        $staffDepartments = $this->_staffDepartmentModel->getStaffDepartmentsByLogin($staffId);
        $staffDepartmentsArray = [];
        if($staffDepartments){
            $staffDepartmentsArray = $staffDepartments->toArray();
            foreach($staffDepartmentsArray as $key => $staffDepartment){
                $lt = new LoginToken();
                // 设置唯一的登录校验码
                $staffId = $staffInfo['staff_id'];
                $departmentId = $staffDepartment['department_id'];
                $token = $lt->setDeptToken($staffId);
                $tokenData = serialize([
					'staff_uuid'	=> app()->gcHelper->gfCreateUUID(),
                    'staff_id' => $staffId,
                    'company_id' => $companyId,
                    'department_id' => $departmentId,
                    'position_id' => $staffDepartment['position_id'],
                    'staff_type' => $staffInfo['staff_type'],
                    'dingTalkId' => $staffInfo['staff_dingding_account'],
                    'dingTalkUnionId' => $staffInfo['staff_dingding_account_unionid'],
                    'userAuth'=>$this->_staffAuthModel->getStaffAuth(
                        $staffId,
                        $departmentId
                    )->toArray()
                ]);
                Redis::setex($token,RedisConsts::REDIS_LOGIN_TOKEN_CONSTS,$tokenData);



                $staffDepartmentsArray[$key]['lo_toc'] = $token;
            }
        }
        return $staffDepartmentsArray;
    }
}